package com.dingwen.treasure.auth.controller;

import com.dingwen.treasure.auth.service.LoginService;
import com.dingwen.treasure.base.constant.RedisConstant;
import com.dingwen.treasure.base.controller.BaseViewController;
import com.dingwen.treasure.base.pojo.vo.Result;
import com.dingwen.treasure.common.redis.service.RedisService;
import com.dingwen.treasure.core.service.CaptchaService;
import com.dingwen.treasure.model.dto.LoginDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


/**
 * 　LoginController: 登录
 * 　@author dingwen
 * 　@since  2022/6/10
 */
@Api(tags = "登录")
@Slf4j
@RestController
@RequestMapping("login")
public class LoginController implements BaseViewController {

    /**
     * 验证码校验服务
     */
    @Resource
    private CaptchaService captchaService;

    /**
     * redis 服务
     */
    @Resource
    private RedisService redisService;

    /**
     * login service
     */
    @Resource
    private LoginService loginService;

    /**
     * 登录 </br>
     * <p>
     * 此处验证码校验也可以放到security的自定义过滤器中实现，
     * 需要单独对不需要验证码对URI配合 web.ignoring() 进行配置。注意
     * </p>
     * <p>//TODO 登录日志</p>
     *
     * @param loginDto 登录数据对象
     * @return token
     */
    @ApiOperation("登录")
    @PostMapping("")
    public Result<String> login(@RequestBody @Validated LoginDto loginDto) {
        // 1. 验证码校验
        String key = RedisConstant.CAPTCHA_KEY.concat(loginDto.getCodeKey());
        captchaService.validate(String.valueOf(loginDto.getCode()), redisService.getCacheObject(key));

        // 2. 登录逻辑 (缓存用户信息、token信息)
        String token = loginService.login(loginDto.getAccount(), loginDto.getPassword());

        // 3. 删除验证码 key
        redisService.deleteObject(key);

        return success(token);
    }

}
